﻿'***********************************************************************
'Magic Chimney Imp (MCI)
'Copyright (C) 2011  David Frendin (david.frendin@gmail.com)
'
'This program is free software: you can redistribute it and/or modify
'it under the terms of the GNU General Public License as published by
'the Free Software Foundation, either version 3 of the License, or
'(at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details.
'
'You should have received a copy of the GNU General Public License
'along with this program.  If not, see <http://www.gnu.org/licenses/>.
'***********************************************************************
Imports System.Text
Imports System.Windows.Forms.DataVisualization.Charting

Public Class frmEditor

    Private MyDeck As DataTable
    Private MySideBoard As DataTable
    Private CardPool As CardPool
    Private ActiveDeck As Deck

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'check environment
        If Not IO.Directory.Exists(Application.StartupPath & "\cardpool") Then
            IO.Directory.CreateDirectory(Application.StartupPath & "\cardpool")
        End If
        If Not IO.Directory.Exists(Application.StartupPath & "\cache") Then
            IO.Directory.CreateDirectory(Application.StartupPath & "\cache")
        End If

        If Not IO.File.Exists(Application.StartupPath & "\cardpool\master.xml") Then
            MsgBox("Could not find master database, loading oracle importer.", MsgBoxStyle.Information)
            Dim dlgOracleImporter As New frmOracleImporter
            dlgOracleImporter.ShowDialog(Me)

            If Not IO.File.Exists(Application.StartupPath & "\cardpool\master.xml") Then
                End
            End If
        End If
        CardPool = New CardPool
        MyDeck = New DataTable
        MyDeck.Columns.Add("MultiverseId")
        MyDeck.Columns.Add("Quantity")
        MyDeck.Columns.Add("Name")
        MyDeck.Columns.Add("Type")
        MyDeck.Columns.Add("Color")
        MyDeck.Columns.Add("Cost")

        MySideBoard = New DataTable
        MySideBoard.Columns.Add("Quantity")
        MySideBoard.Columns.Add("Name")
    End Sub

    Private Sub AddNewCardToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewCardToolStripMenuItem.Click
        Dim dlgCardPool As New frmCardPool
        dlgCardPool.LoadCardPool(Me.CardPool)
        Dim Result As DialogResult = dlgCardPool.ShowDialog(Me)

        If Result = DialogResult.OK Then
            Try
                Dim MultiverseId As String = dlgCardPool.KryptonDataGridViewCardPool.SelectedRows(0).Cells(0).Value.ToString
                Dim cs As New MCI.Deck.CardSlot
                cs.Card = CardPool.GetCard(MultiverseId)
                cs.Quantity = 1
                ActiveDeck.MainDeck.Add(cs)
                'KryptonDataGridView1.AutoGenerateColumns = False
                'KryptonDataGridView1.DataSource = MyDeck

                'ActiveDeck.Sync(KryptonDataGridView1.Rows)
                ActiveDeck.Sync(KryptonDataGridView1)
                RefreshManaCurve()
            Catch ex As Exception
                MsgBox("Could not add card to deck: " & ex.Message)
            End Try
        End If
    End Sub

    Private Sub KryptonDataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles KryptonDataGridView1.CellEndEdit
        ActiveDeck.Sync(KryptonDataGridView1.Rows)
        RefreshManaCurve()
    End Sub

    Private Sub KryptonDataGridView1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonDataGridView1.LostFocus
        KryptonDataGridView1.ClearSelection()
    End Sub

    Private Sub KryptonDataGridView1_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles KryptonDataGridView1.RowsAdded
        For i As Integer = e.RowIndex To e.RowIndex + (e.RowCount - 1)
            Dim TheCard As Card = CardPool.GetCard(KryptonDataGridView1.Rows(i).Cells("MultiverseId").Value)
            If TheCard.Color = String.Empty Then
                KryptonDataGridView1.Rows(i).Cells("Color").Value = My.Resources.ColorIcons.Art
            ElseIf Len(TheCard.Color) > 1 Then
                KryptonDataGridView1.Rows(i).Cells("Color").Value = My.Resources.ColorIcons.gld
            Else
                Select Case LCase(TheCard.Color)
                    Case "r"
                        KryptonDataGridView1.Rows(i).Cells("Color").Value = My.Resources.ColorIcons.r
                    Case "g"
                        KryptonDataGridView1.Rows(i).Cells("Color").Value = My.Resources.ColorIcons.g
                    Case "b"
                        KryptonDataGridView1.Rows(i).Cells("Color").Value = My.Resources.ColorIcons.b
                    Case "u"
                        KryptonDataGridView1.Rows(i).Cells("Color").Value = My.Resources.ColorIcons.u
                    Case "w"
                        KryptonDataGridView1.Rows(i).Cells("Color").Value = My.Resources.ColorIcons.w
                End Select
            End If

            'KryptonDataGridView1.Rows(i).Cells("Cost").Value = My.Resources.ColorIcons.art
        Next
    End Sub

    Private Sub KryptonDataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonDataGridView1.SelectionChanged
        If KryptonDataGridView1.SelectedRows.Count > 0 Then
            Dim MultiverseId As String = KryptonDataGridView1.SelectedRows(0).Cells("MultiverseId").Value.ToString
            Dim MyCard As Card = CardPool.GetCard(MultiverseId)

            KryptonLabelCardName.Text = MyCard.Name
            KryptonLabelCost.Text = MyCard.Cost
            KryptonWrapLabelRules.Text = MyCard.Rules
            KryptonLabelType.Text = MyCard.Type

            CardPool.SetCardImage(PictureBox1, MyCard.MultiverseId)
        End If
    End Sub

    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        Dim dlgCardPool As New frmCardPool
        dlgCardPool.LoadCardPool(Me.CardPool)
        Dim Result As DialogResult = dlgCardPool.ShowDialog(Me)

        If Result = DialogResult.OK Then
            Dim cardname As String = dlgCardPool.KryptonDataGridViewCardPool.SelectedRows(0).Cells(1).Value.ToString
            Dim nr As DataRow = MySideBoard.NewRow
            nr("Quantity") = "1"
            nr("Name") = cardname
            MySideBoard.Rows.Add(nr)
            KryptonDataGridView2.DataSource = MySideBoard
            ActiveDeck.Sync(KryptonDataGridView1.Rows)
            RefreshManaCurve()
        End If
    End Sub

    Private Sub KryptonDataGridView2_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonDataGridView2.LostFocus
        KryptonDataGridView2.ClearSelection()
    End Sub

    Private Sub KryptonDataGridView2_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonDataGridView2.SelectionChanged
        If KryptonDataGridView2.SelectedRows.Count > 0 Then
            Dim MultiverseId As String = KryptonDataGridView2.SelectedRows(0).Cells(0).Value.ToString
            Dim MyCard As Card = CardPool.GetCard(MultiverseId)

            KryptonLabelCardName.Text = MyCard.Name
            KryptonLabelCost.Text = MyCard.Cost
            KryptonWrapLabelRules.Text = MyCard.Rules
            KryptonLabelType.Text = MyCard.Type

            CardPool.SetCardImage(PictureBox1, MyCard.MultiverseId)
        End If
    End Sub

    Private Sub SaveDeckToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveDeckToolStripMenuItem.Click
        SaveFileDialogDeck.InitialDirectory = Application.StartupPath & "\decks\"
        If SaveFileDialogDeck.ShowDialog(Me) = DialogResult.OK Then
            ActiveDeck.Save(SaveFileDialogDeck.FileName)
        End If
        'Dim sb As New StringBuilder
        'sb.AppendLine("<deck>")
        'sb.AppendLine("<meta>")
        'sb.AppendLine("</meta>")
        'sb.AppendLine("<main>")
        'For Each row As DataGridViewRow In KryptonDataGridView1.Rows
        '    Dim drv As DataRowView = row.DataBoundItem
        '    sb.AppendLine(String.Concat("<card multiverseid=""", row.Cells("MultiverseId").Value.ToString & """ quantity=""" & drv.Row("Quantity").ToString & """ />"))
        'Next
        'sb.AppendLine("</main>")
        'sb.AppendLine("<sideboard>")
        'sb.AppendLine("</sideboard>")
        'sb.AppendLine("</deck>")

        'If IO.File.Exists(Application.StartupPath & "\deck.xml") Then
        '    Kill(Application.StartupPath & "\deck.xml")
        'End If
        'Using sw As New IO.StreamWriter(Application.StartupPath & "\deck.xml", IO.FileMode.Create)
        '    sw.Write(sb.ToString)
        'End Using

    End Sub

    Private Sub LoadDeckToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadDeckToolStripMenuItem.Click
        OpenFileDialogDeck.InitialDirectory = Application.StartupPath & "\decks\"
        Dim Result As DialogResult = OpenFileDialogDeck.ShowDialog(Me)
        If Result = DialogResult.OK Then
            ActiveDeck = New Deck
            ActiveDeck.LoadDeck(OpenFileDialogDeck.FileName)
            KryptonSplitContainerMain.Visible = True
            ActiveDeck.Sync(KryptonDataGridView1)
            RefreshManaCurve()
            KryptonHeaderGroupMain.ValuesPrimary.Heading = ActiveDeck.DeckName
        End If
        'Dim ds As New DataSet
        'ds.ReadXml(Application.StartupPath & "\deck.xml")

        'Try
        '    For Each row In ds.Tables("card").Rows
        '        Dim MultiverseId As String = row("multiverseid").ToString
        '        Dim Quantity As Integer = CInt(row("quantity").ToString)

        '        AddCardToMain(MultiverseId, Quantity)
        '    Next
        'Catch
        '    MsgBox("Error loading deck")
        'End Try
    End Sub

    Private Sub AddCardToMain(ByVal MultiverseId As String, Optional ByVal Quantity As Integer = 1)
        Dim TheCard As Card = CardPool.GetCard(MultiverseId)
        Dim nr As DataRow = MyDeck.NewRow
        nr("Quantity") = Quantity
        nr("Name") = TheCard.Name
        nr("MultiverseId") = TheCard.MultiverseId
        nr("Color") = TheCard.Color
        nr("Type") = TheCard.Type
        nr("Cost") = TheCard.Cost
        MyDeck.Rows.Add(nr)
        KryptonDataGridView1.AutoGenerateColumns = False
        KryptonDataGridView1.DataSource = MyDeck
    End Sub

    Private Sub ImportToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportToolStripMenuItem.Click
        Using dlgOracleImporter As New frmOracleImporter
            dlgOracleImporter.ShowDialog(Me)
        End Using
        CardPool = New CardPool
    End Sub

    Private Sub ViewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewToolStripMenuItem.Click
        Dim dlgCardPool As New frmCardPool
        dlgCardPool.LoadCardPool(Me.CardPool)
        dlgCardPool.Show()
    End Sub

    Private Sub NewDeckToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewDeckToolStripMenuItem.Click
        Dim dlg As New dlgNewDeckWizard
        dlg.KryptonTextBoxDeckName.Focus()
        Dim dlgResult As DialogResult = dlg.ShowDialog(Me)

        If dlgResult = DialogResult.OK Then
            KryptonHeaderGroupMain.ValuesPrimary.Heading = dlg.KryptonTextBoxDeckName.Text
            ActiveDeck = New Deck
            ActiveDeck.Sync(KryptonDataGridView1)
            ActiveDeck.DeckName = dlg.KryptonTextBoxDeckName.Text
            ActiveDeck.DeckNotes = dlg.KryptonTextBoxDescription.Text
            KryptonSplitContainerMain.Visible = True
        End If
    End Sub

    Private Sub AboutToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem1.Click
        Dim dlg As New frmAbout
        dlg.ShowDialog(Me)
    End Sub

    Private Sub RefreshManaCurve()
        ' format the chart
        ChartManaCurve.Series(0).Points.Clear()
        ChartManaCurve.Series(1).Points.Clear()
        ChartManaCurve.Series(2).Points.Clear()
        ChartManaCurve.Series(3).Points.Clear()
        ChartManaCurve.Series(4).Points.Clear()
        ChartManaCurve.Series(5).Points.Clear()

        Dim Red(8) As Integer
        Dim Green(8) As Integer
        Dim Black(8) As Integer
        Dim Blue(8) As Integer
        Dim White(8) As Integer
        Dim Colorless(8) As Integer
        Dim useRed As Boolean = False
        Dim useGreen As Boolean = False
        Dim useBlack As Boolean = False
        Dim useBlue As Boolean = False
        Dim useWhite As Boolean = False
        Dim useColorless As Boolean = False



        For Each row As DataGridViewRow In KryptonDataGridView1.Rows
            Dim IsColored As Boolean = False
            Dim drv As DataRowView = row.DataBoundItem
            Dim MultiverseId As String = row.Cells("MultiverseId").Value.ToString
            Dim Quantity As Integer = CInt(drv.Row("Quantity").ToString)
            Dim tc As Card = CardPool.GetCard(MultiverseId)
            If Not tc.Type.Contains("Land") Then
                If tc.CMC > 8 Then
                    tc.CMC = 8
                End If
                If tc.Color.Contains("R") Then
                    Red(tc.CMC) = CInt(Red(tc.CMC)) + Quantity
                    useRed = True
                    IsColored = True
                End If
                If tc.Color.Contains("G") Then
                    Green(tc.CMC) = CInt(Green(tc.CMC)) + Quantity
                    useGreen = True
                    IsColored = True
                End If
                If tc.Color.Contains("B") Then
                    Black(tc.CMC) = CInt(Black(tc.CMC)) + Quantity
                    useBlack = True
                    IsColored = True
                End If
                If tc.Color.Contains("U") Then
                    Blue(tc.CMC) = CInt(Blue(tc.CMC)) + Quantity
                    useBlue = True
                    IsColored = True
                End If
                If tc.Color.Contains("W") Then
                    White(tc.CMC) = CInt(White(tc.CMC)) + Quantity
                    useWhite = True
                    IsColored = True
                End If

                If Not IsColored Then
                    Colorless(tc.CMC) = CInt(Colorless(tc.CMC)) + Quantity
                    useColorless = True
                End If
            End If
        Next

        If useRed Then
            For i = 0 To 8
                ChartManaCurve.Series(0).Points.AddXY(i, CInt(IIf(Red(i) = Nothing, 0, Red(i))))
            Next
        End If

        If useGreen Then
            For i = 0 To 8
                ChartManaCurve.Series(1).Points.AddXY(i, CInt(IIf(Green(i) = Nothing, 0, Green(i))))
            Next
        End If
        If useBlack Then
            For i = 0 To 8
                ChartManaCurve.Series(2).Points.AddXY(i, CInt(IIf(Black(i) = Nothing, 0, Black(i))))
            Next
        End If
        If useBlue Then
            For i = 0 To 8
                ChartManaCurve.Series(3).Points.AddXY(i, CInt(IIf(Blue(i) = Nothing, 0, Blue(i))))
            Next
        End If
        If useWhite Then
            For i = 0 To 8
                ChartManaCurve.Series(4).Points.AddXY(i, CInt(IIf(White(i) = Nothing, 0, White(i))))
            Next
        End If
        If useColorless Then
            For i = 0 To 8
                ChartManaCurve.Series(5).Points.AddXY(i, CInt(IIf(Colorless(i) = Nothing, 0, Colorless(i))))
            Next
        End If


        'ChartManaCurve.Series(0).Points.AddXY(1, 20)
        'ChartManaCurve.Series(0).Points.AddXY(2, 8)
        'ChartManaCurve.Series(0).Points.AddXY(3, 12)

        'ChartManaCurve.Series(1).Points.AddXY(1, 4)
        'ChartManaCurve.Series(1).Points.AddXY(2, 8)
        'ChartManaCurve.Series(1).Points.AddXY(3, 29)

    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        End
    End Sub

    Private Sub PlaytestToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PlaytestToolStripMenuItem.Click
        If ActiveDeck Is Nothing Then
            MsgBox("No deck loaded", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        Dim dlg As New frmPlayTest
        dlg.LoadDeck(ActiveDeck)
        dlg.ShowDialog(Me)
    End Sub
End Class
